
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isScroll: true,
    isEdit: false,
    imgArrData: [],
    showDialog2: false,
    theCount: 1,
    hy: '',
    zl: '',
    idCardImg: '', // 身份证照片 
    jobDataArr: [],
    arrayB: [{
        name: '联系电话',
        require: "input",
        value: ''
      },
      {
        name: '文化程度',
        type: 'input',
        value: '',
        options: ['小学','初中', '高中', '专科', '本科', '研究生', '博士', '博士后']
      }
    ],
    arrayA: [{
        name: '上传身份证照片(清晰的正面照片)',
        require: true,
        type: 'upload',
        value: ''
      },
      {
        name: '从业人员姓名',
        type: 'input',
        value: ''
      },
      {
        name: '身份证号',
        otherName: '注：登录信息',
        require: true,
        type: 'input',
        value: ''
      },
      {
        name: '户籍地址',
        type: 'input',
        value: ''
      },
      {
        name: '性别',
        type: 'select',
        value: '',
        options: ['男', '女']
      }
    ]
  },
  onfocus: function() {
    this.setData({isScroll: false})
  },
  onblur: function () {
    this.setData({isScroll: true})
  },
  inputInfoChange(e) {
    let value = e.detail.value;
    let index = e.currentTarget.dataset.index;
    let type = e.currentTarget.dataset.type;
    console.log('输入1变：', index + ' ' + value)
    let arr = JSON.parse(JSON.stringify(this.data.arrayA))
    arr[index].value = value;
    if (type == 'select') {
      value = value / 1
      arr[index].value = arr[index].options[value];
    }
    this.setData({
      arrayA: arr
    })
  },
  inputInfoChange2(e) {
    let value = e.detail.value;
    let index = e.currentTarget.dataset.index;
    let type = e.currentTarget.dataset.type;
    console.log('输入2变：', index + ' ' + value)
    let arr = JSON.parse(JSON.stringify(this.data.arrayB))
    arr[index].value = value;
    if (type == 'select') {
      value = value / 1
      arr[index].value = arr[index].options[value];
    }
    this.setData({
      arrayB: arr
    })
  },
  // 解析身份证信息,进行处理
  uploadNow(localId) {
    wx.showToast({
      title: '正在解析...'
    })
    let that = this;
    wx.uploadFile({
      filePath: localId,
      name: 'file',
      url: app.commonUrl + '/spec-equipment-mini-special/getInfoByIdCardPicture',
      header: {
        "content-type": "multipart/form-data",
        "cookie": app.cookie,
        "token": app.token,
      },
      method: "POST",
      success: function (res) {
        if (res && res.data && typeof res.data == 'string') {
          let data = JSON.parse(res.data)
          if (data.STATUS == 200) {
            let obj = data.data;
            let arr = JSON.parse(JSON.stringify(that.data.arrayA))
            arr[1].value = obj.username;
            arr[2].value = obj.idNumber;
            arr[3].value = obj.employeeAddress;
            arr[4].value = obj.userGender;
            that.setData({
              arrayA: arr
            })
          } else {
            wx.showToast({
              title: '图片解析失败',
            })
            let arr = JSON.parse(JSON.stringify(that.data.arrayA))
            arr[1].value = '';
            arr[2].value = '';
            arr[3].value = '';
            arr[4].value = '';
            that.setData({
              arrayA: arr
            })
          }
        }
      }
    })
  },
  getHy() {
    wx.request({
      url: app.commonUrl + '/staff-work-type-config/getStaffType',
      header: {
        "content-type": "application/json;charset=UTF-8",
        "cookie": app.cookie,
        "token": app.token,
      },
      data: {},
      method: 'POST',
      success: function (res) {
      }
    })
  },
  aaFun(e) {
    var that = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.setData({
          idCardImg: res.tempFilePaths[0]
        });
        // 马上上传图片
        that.uploadNow(res.tempFilePaths[0])
      }
    })
  },
  bindPicker(e, name) {
    let index = e.detail.value;
    let arr = JSON.parse(JSON.stringify(this.data.arrayA))
    if (name == '文化程度') {
      arr = JSON.parse(JSON.stringify(this.data.arrayB))
    }
    let firstOne;
    let indx = 0;
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].name === name) {
        firstOne = JSON.parse(JSON.stringify(arr[i]))
        indx = i;
        break;
      }
    }
    firstOne.value = firstOne.options[index]
    console.log('indx', indx)
    arr.splice(indx, 1, firstOne)
    if (name == '文化程度') {
      this.setData({
        arrayB: arr
      })
    } else {
      this.setData({
        arrayA: arr
      })
    }
  },
  changeValue(value, name, arr, arrName) {
    let firstOne;
    let indx = 0;
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].name === name) {
        firstOne = JSON.parse(JSON.stringify(arr[i]))
        indx = i;
        break;
      }
    }
    firstOne.value = value
    console.log('indx', indx)
    arr.splice(indx, 1, firstOne)
    this.setData({
      [arrName]: arr
    })
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // this.getHy()

  },
  getHy() {
    let that = this;
    wx.request({
      url: app.commonUrl + "/staff-work-type-config/getIndustryType",
      data: {
        dictType: "permitType"
      },
      header: {
        'content-type': 'application/json',
        'cookie': app.cookie,
        'token': app.token
      },
      method: 'POST',
      success: function (res) {
        if (res) {
          let arr = JSON.parse(JSON.stringify(that.data.arrayA));
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].name == '所属行业') {
              console.log('找到i：', i)
              arr[i].options = res.data.data;
              break;
            }
          }
          // 赋值回去
          that.setData({
            arrayA: arr
          })
        }
      },
      fail: function () {
        console.log('所属行业失败');
      }
    })
  },
  getZL(hy) {
    console.log('选择的行业:', hy)
    let that = this;
    let url = app.commonUrl + "/staff-work-type-config/getWorkType"
    let fullUrl = '/staff-work-type-config/getWorkType'
    wx.request({
      url: fullUrl,
      data: {
        industryType: hy
      },
      header: {
        // 'content-type': 'application/json',
        "content-type": "application/x-www-form-urlencoded",
        'cookie': app.cookie,
        'token': app.token
      },
      method: 'POST',
      success: function (res) {
        
        if (res) {
          let arr = JSON.parse(JSON.stringify(that.data.arrayA));
          let dataArr = ['食品销售员', '测试', '食品采购员'];
          if (res.data && res.data.data && res.data.data.length) {
            dataArr = res.data.data
          }
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].name == '工作种类') {
              console.error('找到i---P：', i, dataArr)
              arr[i].options = dataArr;
              break;
            }
          }
          // 赋值回去
          that.setData({
            arrayA: arr
          })
        }
      },
      fail: function () {
        console.log('所属行业失败');
      }
    })
  },
  getType(hy, zl) {
    let that = this;
    wx.request({
      url: app.commonUrl + "/staff-work-type-config/getStaffType",
      data: {
        "industryType": hy,
        "workType": zl
      },
      header: {
        'content-type': 'application/json',
        'cookie': app.cookie,
        'token': '1_befe8109c4b94a278a559fe99ce44efb'
      },
      method: 'POST',
      success: function (res) {
        // 返回结果: 1 或 2 或 3 
        // 分别代表: 从业人员 执业药师 作业人员
        let arr = ['从业人员证', '执业药师证', '作业人员证'];
        let num = res.data.data
        let name = arr[num - 1]
        console.log("name：", name, num)

        that.setData({
          theCount: num
        })
      },
      fail: function () {
        console.log('是否为作业失败');
      }
    })
  },
  printArr(arr) {
    for (let i = 0; i < arr.length; i++) {
      console.log(arr[i].name, ': ' + arr[i].value)
    }
  },
  sureRegister() {
    this.uploadNowImg([this.data.idCardImg])
  },
  uploadNowImg(localIds) {
    let that = this;
    var localId = localIds.pop();
    console.log("图片地址：", localId)
    if (localId && localId.includes('tmp')) {
      wx.uploadFile({
        filePath: localId,
        name: 'file',
        url: app.commonUrl + '/mini/upload/picture',
        header: {
          "content-type": "multipart/form-data",
          "cookie": app.cookie,
          "token": app.token,
        },
        method: "POST",
        success: function (res) {
          let newOne = JSON.parse(res.data)
          let data = JSON.parse(newOne.data)
          that.setData({
            imgArrData: [...that.data.imgArrData, data[0]]
          })
          if (localIds.length) {
            that.uploadNowImg(localIds)
          } else {
            that.saveData()
          }
        }
      })
    } else {
      this.saveData()
    }
  },
  saveData() {
    let that = this;
    let arr = this.data.arrayA;
    let arr2 = this.data.arrayB;
    this.printArr(arr)
    this.printArr(arr2)
    let arrayA = this.data.arrayA;
    let arrayB = this.data.arrayB;
    let obj = {
      // weChatId: app.globalData.userInfo.openid, //（微信登录 openid）
      weChatId: app.openid,//（微信登录 openid）
      idCardPhoto: JSON.stringify(that.data.imgArrData), //身份证正面照片（获取）
      username: arrayA[1].value, //用户名称（获取）
      idNumber: arrayA[2].value, //身份证号（获取）
      employeeAddress: arrayA[3].value, // 人员户籍地址（获取）
      userGender: arrayA[4].value, // 性别（获取）
      phone: arrayB[0].value, // 从业人员联系电话
      educationLevel: arrayB[1].value, // 文化教育程度
    }
    
    wx.request({
        url: app.commonUrl + '/spec-equipment-mini-special/specEquipmentEmployeeRegister',
        header: {
            "content-type": "application/json;charset=UTF-8",
            // "content-type": "application/x-www-form-urlencoded",
            "cookie": app.cookie,
            "token": app.token,
        },
        data: obj,
        method: 'POST',
        success: function (res) {
            let data = res.data
            if (data.STATUS == 200) {
               wx.navigateTo({
                 url: '../index-home/index',
               })
            } else {
                wx.showToast({
                    title: '获取失败',
                    icon: 'error',
                    duration: 2000
                })
            }
        }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log("选择本地图片时--会自动刷新页面，会跑到onshow这里------",app.regObj)
    if(app.regObj){
      let arrA = [...this.data.arrayA]; // 拷贝一份arrayA
      let arrB = [...this.data.arrayB]  // 拷贝一份arrayB
      // 提取图片
      let obj = app.regObj;
      if(obj.idCardPhoto){
        console.log("地址：",app.commonUrl + jsonToImg(obj.idCardPhoto))
        arrA[0].value = app.commonUrl + jsonToImg(obj.idCardPhoto)
      }
      arrA[1].value = obj.username;
      arrA[2].value = obj.idNumber;
      arrA[3].value = obj.employeeAddress;
      arrA[4].value = obj.userGender;

      arrB[0].value = obj.phone;
      arrB[1].value = obj.educationLevel;
      this.setData({
          idCardImg: arrA[0].value,
          arrayA: arrA,
          arrayB: arrB,
          isEdit: true
        })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})